<template>
  <div class="wifi-config">
    <a-form :model="formState" layout="vertical">
      <a-card title="Wi-Fi设置" :bordered="false">
        <a-form-item name="wifiEnabled">
          <a-space>
            <span>Wi-Fi：</span>
            <a-switch v-model:checked="formState.wifiEnabled" checked-children="开启" un-checked-children="关闭"
              @change="handleWifiSwitch" />
          </a-space>
        </a-form-item>

        <template v-if="formState.wifiEnabled">
          <a-form-item>
            <a-space>
              <a-button type="primary" :loading="scanning" @click="handleScan">
                扫描Wi-Fi
              </a-button>
              <a-button @click="handleAddManual">手动添加</a-button>
            </a-space>
          </a-form-item>

          <a-table :columns="columns" :data-source="wifiList" :loading="scanning" :pagination="false" size="middle"
            style="margin-bottom: 16px">
            <template #signal="{ text }">
              <wifi-outlined v-if="text >= -50" style="color: #52c41a" />
              <wifi-outlined v-else-if="text >= -70" style="color: #faad14" />
              <wifi-outlined v-else style="color: #ff4d4f" />
              {{ text }}dBm
            </template>
            <template #security="{ text }">
              <lock-outlined v-if="text !== 'NONE'" />
              {{ text }}
            </template>
            <template #action="{ record }">
              <a-button type="link" size="small" @click="handleConnect(record)">
                连接
              </a-button>
            </template>
          </a-table>

          <a-divider>已保存的网络</a-divider>

          <a-collapse v-model:activeKey="activeNetworks">
            <a-collapse-panel v-for="network in savedNetworks" :key="network.ssid" :header="network.ssid">
              <template #extra>
                <a-tag :color="network.connected ? 'success' : 'default'">
                  {{ network.connected ? '已连接' : '未连接' }}
                </a-tag>
              </template>
              <a-form layout="vertical">
                <a-form-item label="安全类型">
                  <span>{{ network.security }}</span>
                </a-form-item>
                <a-form-item label="IP地址">
                  <span>{{ network.ipAddress }}</span>
                </a-form-item>
                <a-form-item>
                  <a-space>
                    <a-button type="primary" size="small" @click="handleReconnect(network)"
                      :disabled="network.connected">
                      重新连接
                    </a-button>
                    <a-button danger size="small" @click="handleForget(network)">
                      忘记网络
                    </a-button>
                  </a-space>
                </a-form-item>
              </a-form>
            </a-collapse-panel>
          </a-collapse>
        </template>
      </a-card>
    </a-form>

    <a-modal v-model:visible="connectModalVisible" title="连接到Wi-Fi" @ok="confirmConnect" @cancel="cancelConnect"
      :confirmLoading="connecting">
      <a-form :model="connectForm" layout="vertical">
        <a-form-item label="网络名称 (SSID)">
          <span>{{ selectedNetwork?.ssid }}</span>
        </a-form-item>
        <a-form-item label="密码" name="password" :rules="[{ required: true, message: '请输入Wi-Fi密码' }]">
          <a-input-password v-model:value="connectForm.password" placeholder="请输入Wi-Fi密码" />
        </a-form-item>
        <a-form-item name="autoConnect">
          <a-checkbox v-model:checked="connectForm.autoConnect">
            自动连接
          </a-checkbox>
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal v-model:visible="manualModalVisible" title="手动添加网络" @ok="confirmManual" @cancel="cancelManual">
      <a-form :model="manualForm" layout="vertical">
        <a-form-item label="网络名称 (SSID)" name="ssid" :rules="[{ required: true, message: '请输入网络名称' }]">
          <a-input v-model:value="manualForm.ssid" />
        </a-form-item>
        <a-form-item label="安全类型" name="security">
          <a-select v-model:value="manualForm.security">
            <a-select-option value="NONE">无加密</a-select-option>
            <a-select-option value="WEP">WEP</a-select-option>
            <a-select-option value="WPA/WPA2-PSK">WPA/WPA2-PSK</a-select-option>
            <a-select-option value="WPA3">WPA3</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="密码" name="password"
          :rules="[{ required: manualForm.security !== 'NONE', message: '请输入Wi-Fi密码' }]">
          <a-input-password v-model:value="manualForm.password" :disabled="manualForm.security === 'NONE'" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { defineComponent, reactive, ref } from 'vue';
import { message } from 'ant-design-vue';
import { WifiOutlined, LockOutlined } from '@ant-design/icons-vue';

export default defineComponent({
  name: 'WifiConfig',
  components: {
    WifiOutlined,
    LockOutlined
  },
  setup() {
    const formState = reactive({
      wifiEnabled: true
    });

    const columns = [
      {
        title: '网络名称',
        dataIndex: 'ssid',
        key: 'ssid'
      },
      {
        title: '信号强度',
        dataIndex: 'signal',
        key: 'signal',
        slots: { customRender: 'signal' }
      },
      {
        title: '安全类型',
        dataIndex: 'security',
        key: 'security',
        slots: { customRender: 'security' }
      },
      {
        title: '操作',
        key: 'action',
        slots: { customRender: 'action' }
      }
    ];

    // 模拟数据
    const wifiList = ref([]);
    const savedNetworks = ref([
      {
        ssid: 'Home_WiFi',
        security: 'WPA2-PSK',
        connected: true,
        ipAddress: '192.168.1.100'
      },
      {
        ssid: 'Office_Network',
        security: 'WPA2-PSK',
        connected: false,
        ipAddress: '-'
      }
    ]);

    const scanning = ref(false);
    const connecting = ref(false);
    const connectModalVisible = ref(false);
    const manualModalVisible = ref(false);
    const selectedNetwork = ref(null);
    const activeNetworks = ref(['Home_WiFi']);

    const connectForm = reactive({
      password: '',
      autoConnect: true
    });

    const manualForm = reactive({
      ssid: '',
      security: 'WPA/WPA2-PSK',
      password: ''
    });

    const handleWifiSwitch = (checked) => {
      if (!checked) {
        wifiList.value = [];
      }
    };

    const handleScan = async () => {
      scanning.value = true;
      try {
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 2000));
        wifiList.value = [
          {
            ssid: 'Home_WiFi',
            signal: -45,
            security: 'WPA2-PSK'
          },
          {
            ssid: 'Guest_Network',
            signal: -67,
            security: 'WPA2-PSK'
          },
          {
            ssid: 'Free_WiFi',
            signal: -78,
            security: 'NONE'
          }
        ];
      } catch (error) {
        message.error('扫描失败，请重试');
      } finally {
        scanning.value = false;
      }
    };

    const handleConnect = (network) => {
      selectedNetwork.value = network;
      connectModalVisible.value = true;
    };

    const confirmConnect = async () => {
      connecting.value = true;
      try {
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1500));
        message.success(`已成功连接到 ${selectedNetwork.value.ssid}`);
        connectModalVisible.value = false;
        // 更新已保存网络列表
        const newNetwork = {
          ssid: selectedNetwork.value.ssid,
          security: selectedNetwork.value.security,
          connected: true,
          ipAddress: '192.168.1.101'
        };
        savedNetworks.value = savedNetworks.value.map(n => ({
          ...n,
          connected: n.ssid === newNetwork.ssid
        }));
        if (!savedNetworks.value.find(n => n.ssid === newNetwork.ssid)) {
          savedNetworks.value.push(newNetwork);
        }
        activeNetworks.value = [newNetwork.ssid];
      } catch (error) {
        message.error('连接失败，请检查密码是否正确');
      } finally {
        connecting.value = false;
      }
    };

    const cancelConnect = () => {
      connectModalVisible.value = false;
      connectForm.password = '';
      selectedNetwork.value = null;
    };

    const handleAddManual = () => {
      manualModalVisible.value = true;
    };

    const confirmManual = async () => {
      try {
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000));
        message.success('网络已添加');
        manualModalVisible.value = false;
        savedNetworks.value.push({
          ssid: manualForm.ssid,
          security: manualForm.security,
          connected: false,
          ipAddress: '-'
        });
      } catch (error) {
        message.error('添加失败，请重试');
      }
    };

    const cancelManual = () => {
      manualModalVisible.value = false;
      Object.assign(manualForm, {
        ssid: '',
        security: 'WPA/WPA2-PSK',
        password: ''
      });
    };

    const handleReconnect = async (network) => {
      try {
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1500));
        savedNetworks.value = savedNetworks.value.map(n => ({
          ...n,
          connected: n.ssid === network.ssid
        }));
        message.success(`已重新连接到 ${network.ssid}`);
      } catch (error) {
        message.error('重新连接失败，请重试');
      }
    };

    const handleForget = async (network) => {
      try {
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000));
        savedNetworks.value = savedNetworks.value.filter(n => n.ssid !== network.ssid);
        message.success('已删除网络');
      } catch (error) {
        message.error('删除失败，请重试');
      }
    };

    return {
      formState,
      columns,
      wifiList,
      savedNetworks,
      scanning,
      connecting,
      connectModalVisible,
      manualModalVisible,
      selectedNetwork,
      activeNetworks,
      connectForm,
      manualForm,
      handleWifiSwitch,
      handleScan,
      handleConnect,
      confirmConnect,
      cancelConnect,
      handleAddManual,
      confirmManual,
      cancelManual,
      handleReconnect,
      handleForget
    };
  }
});
</script>

<style scoped>
.wifi-config {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

:deep(.ant-collapse-header) {
  align-items: center !important;
}
</style>
